# Create your views here.
import json
import time
from multiprocessing.pool import ThreadPool

from ES_utils import es_utils
from ES_utils.es_utils import getClient, return_filter
from app.models import *
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from obs import ObsClient
from project.jwt import *
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.authentication import jwt_decode_handler


@method_decorator(csrf_exempt, name="dispatch")
class PaperInfoInitView(APIView):
    def post(self, request):
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        paper_id = request.data.get("paper_id")
        # 论文信息列表
        paper_info = []
        # 作者名称列表
        author_name = []

        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id":paper_id
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))

        if paper_response_json["_source"].get("venue") == None:
            origin = None
        else:
            origin = paper_response_json["_source"].get("venue").get("raw")
        # 获取作者信息
        author_list = paper_response_json["_source"]["authors"]
        for author in author_list:
            if not author.get("name") == None:
                author_name.append(author["name"])
        collect_flag = False
        if Collection.objects.filter(pid=paper_id, uid=user.id):
            collect_flag = True
        paper_info.append({
            "paper_id": paper_id,
            "paper_name": paper_response_json["_source"].get("title"),
            "author_name": author_name,
            "origin": origin,
            "cite_number": paper_response_json["_source"].get("n_citation"),
            "abstract": paper_response_json["_source"].get("abstract"),
            "keyword": paper_response_json["_source"].get("keywords"),
            "domain": paper_response_json["_source"].get("keywords"),
            "DOI": paper_response_json["_source"].get("DOI"),
            "date": paper_response_json["_source"].get("year"),
            "readlist":paper_response_json["_source"].get("url"),
            'collect_flag': collect_flag
        })

        return JsonResponse(
            {
                'info_list': paper_info
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class PaperInfoInitNoTokenView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        # 从token中获取用户id
        paper_id = request.data.get("paper_id")
        # 论文信息列表
        paper_info = []
        # 作者名称列表
        author_name = []

        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id":paper_id
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))

        if paper_response_json["_source"].get("venue") == None:
            origin = None
        else:
            origin = paper_response_json["_source"].get("venue").get("raw")
        # 获取作者信息
        author_list = paper_response_json["_source"]["authors"]
        for author in author_list:
            if not author.get("name") == None:
                author_name.append(author["name"])
        collect_flag = False
        paper_info.append({
            "paper_id": paper_id,
            "paper_name": paper_response_json["_source"].get("title"),
            "author_name": author_name,
            "origin": origin,
            "cite_number": paper_response_json["_source"].get("n_citation"),
            "abstract": paper_response_json["_source"].get("abstract"),
            "keyword": paper_response_json["_source"].get("keywords"),
            "domain": paper_response_json["_source"].get("keywords"),
            "DOI": paper_response_json["_source"].get("DOI"),
            "date": paper_response_json["_source"].get("year"),
            "readlist":paper_response_json["_source"].get("url"),
            'collect_flag': collect_flag
        })
        return JsonResponse(
            {
                'info_list': paper_info
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class AboutListInitView(APIView):
    def post(self, request):
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        # 论文信息列表
        paper_id = request.data.get("paper_id")
        # 相关文献列表
        about_list = []
        '''
        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id": paper_id
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))

        # 获取作者信息
        author_id = []
        author_list = paper_response_json["_source"]["authors"]
        for author in author_list:
            if not author.get("id") == None:
                author_id.append(author["id"])

        # 获取相关论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "authors.id":"5448bc89dabfae87b7e715ef"
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))
        print(paper_response_json["_source"])
        
        for about_paper in papers:
            pid = about_paper.pid
            about_paper = Paper.objects.get(id=pid.id)
            about_list.append({
                'paper_id': about_paper.id,
                'paper_name': about_paper.title,
                'author_id': author.id,
                'author_name': author.name,
                'abstarct': about_paper.abstract,
                'cite_number': about_paper.n_citation,
                'date': about_paper.year,
                'magazine': about_paper.venueraw
            })
        '''
        return JsonResponse(
            {
                'about_list': about_list
            }
        )


@method_decorator(csrf_exempt, name="dispatch")
class AboutNoteInitView(APIView):
    def post(self, request):
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        # 论文信息列表
        paper_id = request.data.get("paper_id")
        # 笔记列表
        note_list = []
        # 笔记获取
        notes = Note.objects.filter(pid=paper_id)
        for note in notes:
            collect_flag = False
            if Collection.objects.filter(nid=note.id, uid=user.id):
                collect_flag = True
            like_flag = False
            if Like.objects.filter(nid=note.id, uid=user.id):
                like_flag = True
            note_list.append({
                'name': note.uid.username,
                'note_id': note.id,
                'id': note.uid.id,
                'image': note.uid.image_url,
                'introduction': note.introduction,
                'likes': note.like_number,
                'collections': note.collection_number,
                'collect_flag': collect_flag,
                'like_flag': like_flag,
                'time': note.time
            })
        return JsonResponse(
            {
                'note_list': note_list
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class AboutNoteInitNoTokenView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        # 论文信息列表
        paper_id = request.data.get("paper_id")
        # 笔记列表
        note_list = []
        # 笔记获取
        collect_flag = False
        like_flag = False
        notes = Note.objects.filter(pid=paper_id)
        for note in notes:
            note_list.append({
                'name': note.uid.username,
                'note_id': note.id,
                'id': note.uid.id,
                'image': note.uid.image_url,
                'introduction': note.introduction,
                'likes': note.like_number,
                'collections': note.collection_number,
                'collect_flag': collect_flag,
                'like_flag': like_flag,
                'time': note.time
            })
        return JsonResponse(
            {
                'note_list': note_list
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class PaperRemarkInitView(APIView):
    def post(self, request):
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        # 论文信息列表
        paper_id = request.data.get("paper_id")
        # 评论获取
        comments = Comment.objects.filter(pid=paper_id)
        pool_size = 8
        pool = ThreadPool(pool_size)  # 创建一个线程池
        para_list = []
        for comment in comments:
            para = (comment, user)
            para_list.append(para)
        total_remark = pool.map(deal_comment, para_list)  # 往线程池中填线程
        pool.close()  # 关闭线程池，不再接受线程
        pool.join()  # 等待线程池中线程全部执行完
        return JsonResponse(
            {
                'remark_list': total_remark,
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class PaperRemarkInitNoTokenView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        # 论文信息列表
        paper_id = request.data.get("paper_id")
        # 评论获取
        comments = Comment.objects.filter(pid=paper_id)
        pool_size = 8
        pool = ThreadPool(pool_size)  # 创建一个线程池
        para_list = []
        for comment in comments:
            para = comment
            para_list.append(para)
        total_remark = pool.map(deal_comment_notoken, para_list)  # 往线程池中填线程
        pool.close()  # 关闭线程池，不再接受线程
        pool.join()  # 等待线程池中线程全部执行完
        return JsonResponse(
            {
                'remark_list': total_remark,
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class PaperInformationView(APIView):
    def post(self, request):
        t = time.time()
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        # 论文信息列表
        paper_info = []
        # 相关文献列表
        about_list = []
        # 评论列表
        remark_list = []
        # 笔记列表
        note_list = []
        # 作者名称列表
        author_name = []
        # 关键词列表
        keyword = []
        # 领域列表
        domain = []
        # url列表
        readlist = []
        total_remark = []
        '''
        paper_id = request.data.get("paper_id")
        
        paper = Paper.objects.get(id=paper_id)

        # 文献信息列表获取
        author2papers = Author2Paper.objects.filter(pid=paper.id)
        for author2paper in author2papers:
            author = Author.objects.get(id=author2paper.aid.id)
            author_name.append(author.name)

        paper2keywords = Paper2Keyword.objects.filter(pid=paper.id)
        for paper2keyword in paper2keywords:
            keyword.append(paper2keyword.keyword)
        domain = keyword

        paper2urls = Paper2Url.objects.filter(pid=paper.id)
        for paper2url in paper2urls:
            readlist.append(paper2url.url)

        collect_flag = False
        if Collection.objects.filter(pid=paper.id, uid=user.id):
            collect_flag = True

        paper_info.append({
            "paper_id": paper.id,
            "paper_name": paper.title,
            "author_name": author_name,
            "origin": paper.venueraw,
            "cite_number": paper.n_citation,
            "abstract": paper.abstract,
            "keyword": keyword,
            "domain": domain,
            "DOI": paper.DOI,
            "date": paper.year,
            "readlist": readlist,
            'collect_flag': collect_flag
        })
        print(f'花费时间1:{time.time() - t:.8f}s')
        # 相关文献获取，只获取第一作者的内容
        author2papers = Author2Paper.objects.get(pid=paper.id)
        author = Author.objects.get(id=author2papers.aid.id)
        papers = Author2Paper.objects.filter(aid=author.id)
        for about_paper in papers:
            pid = about_paper.pid
            about_paper = Paper.objects.get(id=pid.id)
            about_list.append({
                'paper_id': about_paper.id,
                'paper_name': about_paper.title,
                'author_id': author.id,
                'author_name': author.name,
                'abstarct': about_paper.abstract,
                'cite_number': about_paper.n_citation,
                'date': about_paper.year,
                'magazine': about_paper.venueraw
            })
        print(f'花费时间2:{time.time() - t:.8f}s')

        # 评论获取
        comments = Comment.objects.filter(pid=paper_id)
        total_remark = []
        pool_size = 10
        pool = ThreadPool(pool_size)  # 创建一个线程池
        para_list = []
        for comment in comments:
            para = (comment, user)
            para_list.append(para)
        total_remark = pool.map(deal_comment, para_list)  # 往线程池中填线程
        pool.close()  # 关闭线程池，不再接受线程
        pool.join()  # 等待线程池中线程全部执行完

        print(f'花费时间3:{time.time() - t:.8f}s')
        # 笔记获取
        notes = Note.objects.filter(pid=paper_id)
        for note in notes:
            collect_flag = False
            if Collection.objects.filter(nid=note.id, uid=user.id):
                collect_flag = True
            like_flag = False
            if Like.objects.filter(nid=note.id, uid=user.id):
                like_flag = True
            note_list.append({
                'name': note.uid.username,
                'note_id': note.id,
                'id': note.uid.id,
                'image': note.uid.image_url,
                'introduction': note.introduction,
                'likes': note.like_number,
                'collections': note.collection_number,
                'collect_flag': collect_flag,
                'like_flag': like_flag,
                'time': note.time
            })
        print(f'花费时间4:{time.time() - t:.8f}s')
        '''
        return JsonResponse(
            {
                'info_list': paper_info,
                'about_list': about_list,
                'remark_list': total_remark,
                'note_list': note_list
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class PaperCollectionView(APIView):
    def post(self, request):
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)

        paper_id = request.data.get("paper_id")
        note_id = request.data.get("note_id")
        op = request.data.get("op")

        if op == "1":
            if note_id == "":
                if Collection.objects.filter(pid=paper_id, uid=user_id).exists():
                    return JsonResponse(
                        {
                            'error_number': '-1',
                            'msg': '已经收藏'
                        }
                    )

                else:
                    new_collection = Collection(pid=paper_id, uid=user, visible_type=False)
                    new_collection.save()
                    return JsonResponse(
                        {
                            'error_number': '0',
                            'msg': '收藏成功'
                        }
                    )
            elif paper_id == "":
                note = Note.objects.get(id=note_id)
                if Collection.objects.filter(nid=note_id, uid=user_id).exists():
                    return JsonResponse(
                        {
                            'error_number': '-1',
                            'msg': '已经收藏'
                        }
                    )
                else:
                    new_collection = Collection(nid=note, uid=user, visible_type=False)
                    new_collection.save()
                    note.collection_number = note.collection_number + 1
                    note.save()
                    return JsonResponse(
                        {
                            'error_number': '0',
                            'msg': '收藏成功'
                        }
                    )
        else:
            if note_id == "":
                collection = Collection.objects.get(pid=paper_id, uid=user_id)
                collection.delete()
            elif paper_id == "":
                note = Note.objects.get(id=note_id)
                collection = Collection.objects.get(nid=note_id, uid=user_id)
                collection.delete()
                note.collection_number = note.collection_number - 1
                note.save()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '取消收藏成功'
                }
            )


@method_decorator(csrf_exempt, name="dispatch")
class PaperQuoteView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        paper_id = request.data.get("paper_id")
        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id":paper_id
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))
        if paper_response_json["_source"].get("venue") == None:
            origin = ""
        else:
            origin = paper_response_json["_source"].get("venue").get("raw")
        title = paper_response_json["_source"].get("title")
        venue_name = origin
        page_start = paper_response_json["_source"].get("page_start")
        page_end = paper_response_json["_source"].get("page_end")
        year = paper_response_json["_source"].get("year")
        DOI = paper_response_json["_source"].get("DOI")
        url = paper_response_json["_source"].get("url")
        # 获取作者信息
        author_list = paper_response_json["_source"]["authors"]
        author_names = []
        for author in author_list:
            if not author.get("name") == None:
                author_names.append(author["name"])
        # [1]赵鹏,郑玉琪,田进伟,刘新新.阿克曼氏菌与动脉粥样硬化关系的研究进展[J/OL].中国动脉硬化杂志:1-9[2022-11-27].http://kns.cnki.net/kcms/detail/43.1262.r.20221111.1315.004.html
        # 主要责任者. 题名：其它题名信息[文献类型标识符/文献载体标识符]. 其它责任者. 版本项. 版本地: 出版者, 出版年: 引文页码[引用日期]. 获取和访问途径. 数字对象唯一标识符.
        quote_G = "[1]"
        for author_name in author_names:
            quote_G = quote_G + author_name + ","
        quote_G = quote_G[:-1]
        quote_G = quote_G + '.' + title + "." + venue_name + ":"
        if not year == None:
            quote_G = quote_G + str(year) + ":"
        if not page_start == None and not page_end == None:
            quote_G = quote_G + page_start + "-" + page_end
        quote_G = quote_G + "."
        if not url == None:
            quote_G = quote_G + url[0] + "."
        if not DOI == None:
            quote_G = quote_G + DOI + "."

        # [1]赵鹏, et al."阿克曼氏菌与动脉粥样硬化关系的研究进展." 中国动脉硬化杂志 ..
        if len(author_names) == 1:
            quote_M = "[1]" + author_names[0] + "."
        elif len(author_names) == 2:
            quote_M = "[1]" + author_names[0] + ",and" + author_names[1] + "."
        else:
            quote_M = "[1]" + author_names[0] + "et al."

        quote_M = quote_M + '"' + title + '"' + venue_name + ","

        if not year == None:
            quote_M = quote_M + str(year) + ":"
        if not page_start == None and not page_end == None:
            quote_M = quote_M + page_start + "-" + page_end
        quote_M = quote_M + "."

        #	[1]赵鹏,郑玉琪,田进伟 & 刘新新..阿克曼氏菌与动脉粥样硬化关系的研究进展. 中国动脉硬化杂志.
        if len(author_names) == 1:
            quote_A = "[1]" + author_names[0] + "."
        elif len(author_names) == 2:
            quote_A = "[1]" + author_names[0] + "&" + author_names[1] + "."
        else:
            quote_A = "[1]"
            for index in range(len(author_names)):
                if not index == len(author_names):
                    quote_A = quote_A + author_names[index] + ","
                else:
                    quote_A = quote_A[:-1]
                    quote_A = quote_A + "&" + author_names[index] + "."
        if not year == None:
            quote_A = quote_A + "(" + str(year) + ")" + "."
        quote_A = quote_A + title + "." + venue_name
        if not page_start == None and not page_end == None:
            quote_A = quote_A + "," + page_start + "-" + page_end
        quote_A = quote_A + "."
        quote = []
        quote.append({
            'type': 'GB/T 7714-2015',
            'content': quote_G,
        })
        quote.append({
            'type': 'MLA格式引文',
            'content': quote_M,
        })
        quote.append({
            'type': 'APA格式引文',
            'content': quote_A,
        })
        return JsonResponse(
            {
                'quote': quote
            }
        )


@method_decorator(csrf_exempt, name="dispatch")
class ESSearchView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]

    def post(self, request):

        params = request.data

        try:
            ret = es_utils.forwardRequest(params)
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': 'success',
                    'data': ret
                }
            )

        except TypeError as e:
            return JsonResponse(
                {
                    'error_number': '-1',
                    'msg': '未知错误'
                }
            )

        pass


@method_decorator(csrf_exempt, name="dispatch")
class PaperComplainView(APIView):
    def post(self, request):
        paper_id = request.data.get("paper_id")
        introduction = request.data.get("introduction")
        image = request.FILES.get('img')
        image_name = image.name
        # image_name = request.FILES.get('img').name
        # image = request.FILES.get('img').read().decode("latin1")
        contact = request.data.get("contact")

        ## 文件上传到存储数据库
        obsClient = ObsClient(
            access_key_id='KCMJB0LFG2AQTSTMEOHM',  # 刚刚下载csv文件里面的Access Key Id
            secret_access_key='HJ3dwKTrTV0NmZaR7z6S2FeeI1Y0k6N2Cbdw0Fka',  # 刚刚下载csv文件里面的Secret Access Key
            server='https://obs.cn-north-4.myhuaweicloud.com/'  # 这里的访问域名就是我们在桶的基本信息那里记下的东西
            # endpoint:
            # https://obs.cn-north-4.myhuaweicloud.com
            # 访问域名:
            # https://obs-0dcd.obs.cn-north-4.myhuaweicloud.com
        )
        upload_response = obsClient.putObject("obs-0dcd", image_name, image)
        ## 保存路由
        ## https:// + 自己创建的桶对象名字 + 服务节点endpoint + 文件名
        # download_response = obsClient.getObject("obs-0dcd", image_name ,image)
        # print(download_response.status)
        image_url = "https://" + "obs-0dcd" + "." + "obs.cn-north-4.myhuaweicloud.com" + "/" + image_name
        # print(image_url)
        new_complain = Complain(pid=paper_id,contact=contact, image_url=image_url, introduction=introduction)
        new_complain.save()
        obsClient.close()
        return JsonResponse(
            {
                'error_number': '0',
                'msg': '投诉成功'
            }
        )


@method_decorator(csrf_exempt, name="dispatch")
class UploadNoteView(APIView):
    def post(self, request):
        paper_id = request.data.get("paper_id")
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        introduction = request.data.get("introduction")
        pdf = request.FILES.get('pdf')
        pdf_name = pdf.name
        obsClient = ObsClient(
            access_key_id='KCMJB0LFG2AQTSTMEOHM',
            secret_access_key='HJ3dwKTrTV0NmZaR7z6S2FeeI1Y0k6N2Cbdw0Fka',
            server='https://obs.cn-north-4.myhuaweicloud.com/'
        )
        upload_response = obsClient.putObject("obs-0dcd", pdf_name, pdf)
        image_url = "https://" + "obs-0dcd" + "." + "obs.cn-north-4.myhuaweicloud.com" + "/" + pdf_name
        new_note = Note(pid=paper_id, uid=user, introduction=introduction, image_url=image_url)
        new_note.save()
        obsClient.close()
        return JsonResponse(
            {
                'error_number': '0',
                'msg': '创建笔记成功'
            }
        )


@method_decorator(csrf_exempt, name="dispatch")
class AuthorInitView(APIView):
    def post(self, request):
        author_info = []
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        paper_num = 0
        # 作者机构信息，一个学者可能对应多个机构
        orgnizations = []
        # 获取作者信息
        if not note.uid.aid == "":
            print(note.uid.aid)
            Json_authorbody = {
                "query": {
                    "match": {
                        "id": note.uid.aid
                    }
                }
            }
            client = getClient()
            author_response = return_filter(client.search(index="author", body=Json_authorbody))[0]
            author_response_json = json.loads(json.dumps(author_response))
            orgnizations = author_response_json["_source"].get("orgs")
        note_num = len(Note.objects.filter(uid=note.uid.id))
        subscribe_flag = False
        if Subscribe.objects.filter(uid_0=user.id, uid_1=note.uid.id).exists():
            subscribe_flag = True
        # 笔记作者信息
        author_info.append({
            'id': note.uid.id,
            'image': note.uid.image_url,
            'name': note.uid.username,
            'institution': orgnizations,
            'paper_num': paper_num,
            'note_num': note_num,
            'subscribe_flag': subscribe_flag
        })
        return JsonResponse(
            {
                'author_info': author_info
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class AuthorInitNoTokenView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        author_info = []
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        paper_num = 0
        # 作者机构信息，一个学者可能对应多个机构
        orgnizations = []
        # 获取作者信息
        if not note.uid.aid == "":
            print(note.uid.aid)
            Json_authorbody = {
                "query": {
                    "match": {
                        "id": note.uid.aid
                    }
                }
            }
            client = getClient()
            author_response = return_filter(client.search(index="author", body=Json_authorbody))[0]
            author_response_json = json.loads(json.dumps(author_response))
            orgnizations = author_response_json["_source"].get("orgs")
        note_num = len(Note.objects.filter(uid=note.uid.id))
        subscribe_flag = False
        # 笔记作者信息
        author_info.append({
            'id': note.uid.id,
            'image': note.uid.image_url,
            'name': note.uid.username,
            'institution': orgnizations,
            'paper_num': paper_num,
            'note_num': note_num,
            'subscribe_flag': subscribe_flag
        })
        return JsonResponse(
            {
                'author_info': author_info
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class OtherNoteInitView(APIView):
    def post(self, request):
        author_info = []
        other_note = []
        note_info = []
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        paper_num = 0
        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id": note.pid
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))
        # 作者其他笔记
        notes = Note.objects.filter(uid=note.uid.id)
        for note in notes:
            comment_number = note.comment_number
            collection_number = note.collection_number
            collect_flag = False
            if Collection.objects.filter(nid=note.id, uid=user.id):
                collect_flag = True
            like_flag = False
            if Like.objects.filter(nid=note.id, uid=user.id):
                like_flag = True
            other_note.append({
                'note_id': note.id,
                'paper_id': paper_response_json["_source"].get("id"),
                'paper_name': paper_response_json["_source"].get("title"),
                'introduction': note.introduction,
                'likes': note.like_number,
                'remarks': comment_number,
                'collections': collection_number,
                'collect_flag': collect_flag,
                'like_flag': like_flag,
                'time': note.time
            })
        return JsonResponse(
            {
                'other_note': other_note
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class OtherNoteInitNoTokenView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        author_info = []
        other_note = []
        note_info = []
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        paper_num = 0
        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id": note.pid
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))
        # 作者其他笔记
        notes = Note.objects.filter(uid=note.uid.id)
        for note in notes:
            comment_number = note.comment_number
            collection_number = note.collection_number
            collect_flag = False
            like_flag = False
            other_note.append({
                'note_id': note.id,
                'paper_id': paper_response_json["_source"].get("id"),
                'paper_name': paper_response_json["_source"].get("title"),
                'introduction': note.introduction,
                'likes': note.like_number,
                'remarks': comment_number,
                'collections': collection_number,
                'collect_flag': collect_flag,
                'like_flag': like_flag,
                'time': note.time
            })
        return JsonResponse(
            {
                'other_note': other_note
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class NoteInfoInitView(APIView):
    def post(self, request):
        author_info = []
        other_note = []
        note_info = []
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        paper_num = 0
        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id": note.pid
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))
        collect_flag = False
        if Collection.objects.filter(nid=note.id, uid=user.id):
            collect_flag = True
        like_flag = False
        if Like.objects.filter(nid=note.id, uid=user.id):
            like_flag = True
        note_info.append({
            'note_id': note.id,
            'paper_id': paper_response_json["_source"].get("id"),
            'paper_name': paper_response_json["_source"].get("title"),
            'note_url': note.image_url,
            'likes': note.like_number,
            'remarks': note.comment_number,
            'collections': note.collection_number,
            'collect_flag': collect_flag,
            'like_flag': like_flag,
            'time': note.time
        })
        return JsonResponse(
            {
                'note_info': note_info
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class NoteInfoInitNoTokenView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        author_info = []
        other_note = []
        note_info = []
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        paper_num = 0
        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id": note.pid
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))
        collect_flag = False
        like_flag = False
        note_info.append({
            'note_id': note.id,
            'paper_id': paper_response_json["_source"].get("id"),
            'paper_name': paper_response_json["_source"].get("title"),
            'note_url': note.image_url,
            'likes': note.like_number,
            'remarks': note.comment_number,
            'collections': note.collection_number,
            'collect_flag': collect_flag,
            'like_flag': like_flag,
            'time': note.time
        })
        return JsonResponse(
            {
                'note_info': note_info
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class NoteRemarkInitView(APIView):
    def post(self, request):
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        # 评论获取
        comments = Comment.objects.filter(nid=note.id)
        pool_size = 10
        pool = ThreadPool(pool_size)  # 创建一个线程池
        para_list = []
        for comment in comments:
            para = (comment, user)
            para_list.append(para)
        total_remark = pool.map(deal_comment, para_list)  # 往线程池中填线程
        pool.close()  # 关闭线程池，不再接受线程
        pool.join()  # 等待线程池中线程全部执行完
        return JsonResponse(
            {
                'remark_list': total_remark
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class NoteRemarkInitNoTokenView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        # 评论获取
        comments = Comment.objects.filter(nid=note.id)
        pool_size = 10
        pool = ThreadPool(pool_size)  # 创建一个线程池
        para_list = []
        for comment in comments:
            para = comment
            para_list.append(para)
        total_remark = pool.map(deal_comment_notoken, para_list)  # 往线程池中填线程
        pool.close()  # 关闭线程池，不再接受线程
        pool.join()  # 等待线程池中线程全部执行完
        return JsonResponse(
            {
                'remark_list': total_remark
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class NoteInitView(APIView):
    def post(self, request):
        t = time.time()
        author_info = []
        other_note = []
        note_info = []
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        paper_num = 0

        # 作者机构信息，一个学者可能对应多个机构
        orgnizations = []
        # 获取作者信息
        if not note.uid.aid == None:
            Json_authorbody = {
                "query": {
                    "match": {
                        "id": note.uid.aid
                    }
                }
            }
            client = getClient()
            author_response = return_filter(client.search(index="paper", body=Json_authorbody))[0]
            author_response_json = json.loads(json.dumps(author_response))
            orgnizations = author_response_json["_source"].get("orgs")
        note_num = len(Note.objects.filter(uid=note.uid.id))
        subscribe_flag = False
        if Subscribe.objects.filter(uid_0=user.id, uid_1=note.uid.id).exists():
            subscribe_flag = True
        # 笔记作者信息
        author_info.append({
            'id': note.uid.id,
            'image': note.uid.image_url,
            'name': note.uid.username,
            'institution': orgnizations,
            'paper_num': paper_num,
            'note_num': note_num,
            'subscribe_flag': subscribe_flag
        })

        # 获取论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "id": note.pid
                }
            }
        }
        client = getClient()
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
        paper_response_json = json.loads(json.dumps(paper_response))
        # 作者其他笔记
        notes = Note.objects.filter(uid=note.uid.id)
        for note in notes:
            comment_number = note.comment_number
            collection_number = note.collection_number
            collect_flag = False
            if Collection.objects.filter(nid=note.id, uid=user.id):
                collect_flag = True
            like_flag = False
            if Like.objects.filter(nid=note.id, uid=user.id):
                like_flag = True
            other_note.append({
                'note_id': note.id,
                'paper_id': paper_response_json["_source"].get("id"),
                'paper_name': paper_response_json["_source"].get("title"),
                'introduction': note.introduction,
                'likes': note.like_number,
                'remarks': comment_number,
                'collections': collection_number,
                'collect_flag': collect_flag,
                'like_flag': like_flag,
                'time': note.time
            })

        # 笔记信息
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        # 评论获取
        comments = Comment.objects.filter(nid=note.id)
        pool_size = 10
        pool = ThreadPool(pool_size)  # 创建一个线程池
        para_list = []
        for comment in comments:
            para = (comment, user)
            para_list.append(para)
        total_remark = pool.map(deal_comment, para_list)  # 往线程池中填线程
        pool.close()  # 关闭线程池，不再接受线程
        pool.join()  # 等待线程池中线程全部执行完

        collect_flag = False
        if Collection.objects.filter(nid=note.id, uid=user.id):
            collect_flag = True
        like_flag = False
        if Like.objects.filter(nid=note.id, uid=user.id):
            like_flag = True
        note_info.append({
            'note_id': note.id,
            'paper_id': paper_response_json["_source"].get("id"),
            'note_url': note.image_url,
            'remark_list': total_remark,
            'likes': note.like_number,
            'remarks': note.comment_number,
            'collections': note.collection_number,
            'paper_name': paper_response_json["_source"].get("title"),
            'collect_flag': collect_flag,
            'like_flag': like_flag,
            'time': note.time
        })
        return JsonResponse(
            {
                'author_info': author_info,
                'other_note': other_note,
            }
        )


@method_decorator(csrf_exempt, name="dispatch")
class UploadCommentView(APIView):
    def post(self, request):
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        receiver_id = request.data.get("receiver_id")
        content = request.data.get("comments")
        paper_id = request.data.get("paper_id")
        note_id = request.data.get("note_id")
        response_id = request.data.get("remark_id")
        root_id = request.data.get("root_id")
        # 笔记的评论
        if paper_id == "":
            note = Note.objects.get(id=note_id)
            note.collection_number = note.collection_number + 1
            note.save()
            sender = User.objects.get(id=user_id)
            if receiver_id == "-1":
                new_comment = Comment(uid_0=sender, content=content, nid=note, response_id=response_id, type=0)
            else:
                receiver = User.objects.get(id=receiver_id)
                new_comment = Comment(uid_0=sender, uid_1=receiver, content=content, nid=note, response_id=response_id,
                                      type=1)
            new_comment.save()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '评论成功'
                }
            )
        elif note_id == "":
            sender = User.objects.get(id=user_id)
            if receiver_id == "-1":
                new_comment = Comment(uid_0=sender, content=content, pid=paper_id, response_id=response_id, type=0)
            else:
                receiver = User.objects.get(id=receiver_id)
                new_comment = Comment(uid_0=sender, uid_1=receiver, content=content, pid=paper_id, response_id=response_id,
                                      type=1)
            new_comment.save()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '评论成功'
                }
            )
        else:
            print("传参错误！")
            return JsonResponse(
                {
                    'error_number': '-1',
                    'msg': '评论失败'
                }
            )


@method_decorator(csrf_exempt, name="dispatch")
class LikeItView(APIView):
    def post(self, request):
        comment_id = request.data.get("comment_id")
        note_id = request.data.get("note_id")
        op = request.data.get("op")
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)

        # 点赞评论
        if op == "1":
            # 点赞评论
            if note_id == "":
                comment = Comment.objects.get(id=comment_id)
                comment.like_number = comment.like_number + 1
                comment.save()
                new_like = Like(cid=comment, uid=user)
                new_like.save()
                return JsonResponse(
                    {
                        'error_number': '0',
                        'msg': '点赞成功'
                    }
                )
            # 点赞笔记
            elif comment_id == "":
                note = Note.objects.get(id=note_id)
                note.like_number = note.like_number + 1
                note.save()
                new_like = Like(nid=note, uid=user)
                new_like.save()
                return JsonResponse(
                    {
                        'error_number': '0',
                        'msg': '点赞成功'
                    }
                )
            else:
                print("重复传参！")
                return JsonResponse(
                    {
                        'error_number': '-1',
                        'msg': '点赞失败'
                    }
                )
        else:
            if note_id == "":
                comment = Comment.objects.get(id=comment_id)
                comment.like_number = comment.like_number - 1
                comment.save()
                like = Like.objects.filter(cid=comment_id, uid=user_id)
                like.delete()
            elif comment_id == "":
                note = Note.objects.get(id=note_id)
                note.like_number = note.like_number - 1
                note.save()
                like = Like.objects.filter(nid=note_id, uid=user_id)
                like.delete()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '取消点赞成功'
                }
            )


@method_decorator(csrf_exempt, name="dispatch")
class TipOffView(APIView):
    def post(self, request):
        comment_id = request.data.get("comment_id")
        note_id = request.data.get("note_id")
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)

        # 举报评论
        if note_id == "":
            comment = Comment.objects.get(id=comment_id)
            comment.is_reported = True
            comment.save()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '举报成功'
                }
            )
        # 举报笔记
        elif comment_id == "":
            note = Note.objects.get(id=note_id)
            note.is_reported = True
            note.save()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '举报成功'
                }
            )
        else:
            print("重复传参！")
            return JsonResponse(
                {
                    'error_number': '-1',
                    'msg': '举报失败'
                }
            )


@method_decorator(csrf_exempt, name="dispatch")
class SubscribeView(APIView):
    def post(self, request):
        # 从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        author_id = request.data.get("author_id")
        op = request.data.get("op")
        author = User.objects.get(id=author_id)
        if op == "1":
            new_subscribe = Subscribe(uid_0=user, uid_1=author)
            new_subscribe.save()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '订阅成功'
                }
            )
        else:
            subscribe = Subscribe.objects.get(uid_0=user, uid_1=author)
            subscribe.delete()
            return JsonResponse(
                {
                    'error_number': '0',
                    'msg': '取消订阅成功'
                }
            )

def deal_comment(para_list):
    remark_list = []
    total_remark = []
    comment = para_list[0]
    user_0 = User.objects.get(id=comment.uid_0.id)
    like_flag = False
    likes = Like.objects.filter(cid=comment.id, uid=para_list[1])
    if likes.exists():
        like_flag = True
    if comment.uid_1 == None:
        user_1_username = ""
        user_1_id = -1
    else:
        user_1 = User.objects.get(id=comment.uid_1.id)
        user_1_username = user_1.username
        user_1_id = user_1.id
    return ({
        'id': comment.id,
        'flag': comment.type,
        'sender_id': comment.uid_0.id,
        'image': comment.uid_0.image_url,
        'res_id': user_1_id,
        'likes': comment.like_number,
        'comment': comment.content,
        'name': user_0.username,
        'res_name': user_1_username,
        'remark_id': comment.response_id,
        'like_flag': like_flag,
        'time': comment.time
    })

def deal_comment_notoken(para_list):
    remark_list = []
    total_remark = []
    comment = para_list
    user_0 = User.objects.get(id=comment.uid_0.id)
    like_flag = False
    if comment.uid_1 == None:
        user_1_username = ""
        user_1_id = -1
    else:
        user_1 = User.objects.get(id=comment.uid_1.id)
        user_1_username = user_1.username
        user_1_id = user_1.id
    return ({
        'id': comment.id,
        'flag': comment.type,
        'sender_id': comment.uid_0.id,
        'image': comment.uid_0.image_url,
        'res_id': user_1_id,
        'likes': comment.like_number,
        'comment': comment.content,
        'name': user_0.username,
        'res_name': user_1_username,
        'remark_id': comment.response_id,
        'like_flag': like_flag,
        'time': comment.time
    })